package com.haiermzj.client;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;


/**
 * @ClassName: SocketBase
 * @Description: socket tcp
 **/
public class SocketBase {

    private static final int BUF_SIZE = 1024 * 5;//一次接收缓冲区大小

    private Socket mSocket;//socket连接对象
    private DataOutputStream out;//socket连接对象
    private DataInputStream in;//输入流
    private SocketCallback callback;//信息回调接口
    private Context context;

    private int timeout = 30 * 1000;

    /**
     * @param callback                  回调接口：各通信协议实现各自的回调接口
     * @param socketConnectTestActivity
     * @Description: 构造方法传入信息回调接口对象
     */
    public SocketBase(SocketCallback callback, Context context) {
        this.callback = callback;
        this.context = context;
    }

    public void setTimeOut(int timeout) {
        this.timeout = timeout;
    }


    /**
     * @param ip   IP地址
     * @param port 端口
     * @throws Exception
     * @Description: 连接网络服务器
     */
    public void connect(String ip, int port) throws Exception {
        mSocket = new Socket();
        mSocket.setTcpNoDelay(true);
        SocketAddress address = new InetSocketAddress(ip, port);
        mSocket.connect(address, timeout);
        if (mSocket.isConnected()) {
            out = new DataOutputStream(mSocket.getOutputStream());//获取网络输出流
            in = new DataInputStream(mSocket.getInputStream());//获取网络输入流
            callback.connected();//连接上后的回调
        }
    }


    /**
     * @return void
     * @Description: 断开网络
     */
    public void disConnect() {
        try {
            if (mSocket != null) {
                if (!mSocket.isInputShutdown()) {
                    mSocket.shutdownInput();
                }
                if (!mSocket.isOutputShutdown()) {
                    mSocket.shutdownOutput();
                }
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                mSocket.close();//关闭socket
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            callback.disconnect();//断开连接后的回调
            out = null;
            in = null;
            mSocket = null;//置空socket对象
        }
    }


    /**
     * @param buffer 信息字节数据
     * @throws IOException
     * @Description: 发送数据
     */
    public boolean write(byte[] buffer) throws IOException {
        if (buffer == null || buffer.length <= 0) {
            return false;
        }
        if (out != null) {
            out.write(buffer);
            out.flush();
            return true;
        } else {
            return false;
        }
    }

    /**
     * @throws IOException
     * @Description: 读取网络数据
     */
    public void read() throws IOException {
        if (in != null) {
            byte[] buffer = new byte[BUF_SIZE];//缓冲区字节数组，信息不能大于此缓冲区
            byte[] tmpBuffer;// 临时缓冲区
            int len = 0;//读取长度

            File file = new File("/sdcard" + File.separator + System.currentTimeMillis() + ".png");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            while ((len = in.read(buffer)) > 0) {
                Log.e("---", "read: 回传了字节流" + len);
                fileOutputStream.write(buffer, 0, len);
                fileOutputStream.flush();
//				tmpBuffer = new byte[len];//创建临时缓冲区
//				System.arraycopy(buffer, 0, tmpBuffer, 0, len);//将数据拷贝到临时缓冲区
//				callback.receive(tmpBuffer);//调用回调接口传入得到的数据--》进行处理
//				tmpBuffer = null;
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(Uri.fromFile(file));
                context.sendBroadcast(intent);
            }

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());


        }
    }
}

 
